﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Syx.Webapi.Extensions;

namespace ZhongLiang.Core.Helpers
{
    public static class HttpHelper
    {
        public static async void Get(this string url)
        {
            using (var client=new HttpClient())
            {
                var result = await client.GetAsync(url);
                var ss= await result.Content.ReadAsStringAsync();
            }
        }

        public static async Task<Tuple<bool, string>> Post(this string url, object postData, int iWaitTime = 10000)
        {
            return await Post(url, JsonConvert.SerializeObject(postData), iWaitTime);
        }

        public static async Task<Tuple<bool,string>> Post(this string url, string postData, int iWaitTime = 10000)
        {
            using (var client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromMilliseconds(iWaitTime);
                if (url.StartsWith("https"))
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                //ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

                if (postData.IsNullOrWhiteSpace()) postData = "";
                HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };

                //httpContent.Headers.Add("Accept", "application/json, text/plain, */*");
                //httpContent.Headers.Add("Referer", "https://10.249.6.18:8884/countryCollection.html");
                //httpContent.Headers.Add("Accept-Language", "zh-CN");
                //httpContent.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
                //httpContent.Headers.Add("Cache-Control", "no-cache");
                //httpContent.Headers.Add("Accept-Encoding", "gzip, deflate");

                try
                {
                    NlogHelper._logger.Info($"请求地址{url}>>>>>>>>>>>>>>>>>>>>>>>>>");
                    NlogHelper._logger.Info(postData);
                    HttpContent content = new StringContent(postData,Encoding.UTF8);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();//用来抛异常的
                    string responseBody = await response.Content.ReadAsStringAsync();
                    NlogHelper._logger.Info(responseBody);
                    NlogHelper._logger.Info($"【完成】请求地址{url}<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    return new Tuple<bool, string>(true, responseBody);
                }
                catch (WebException e)
                {
                    NlogHelper._logger.Warn(e);
                    NlogHelper._logger.Info($"【错误】请求地址{url}<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    return new Tuple<bool, string>(false, e.Message);
                }
                catch (Exception e)
                {
                    NlogHelper._logger.Error(e);
                    NlogHelper._logger.Info($"【错误】请求地址{url}<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    return new Tuple<bool, string>(false, e.Message);
                }
            }
        }


        public static async Task<Tuple<bool, string>> PostSopa(this string url, string postData, int iWaitTime = 10000) {
            using (var client = new HttpClient()) {
                client.Timeout = TimeSpan.FromMilliseconds(iWaitTime);
                if (url.StartsWith("https")) {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                //ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

                if (postData.IsNullOrWhiteSpace()) postData = "";
                HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("text/xml") { CharSet = "utf-8" };

                try {
                    NlogHelper._logger.Info($"请求地址{url}>>>>>>>>>>>>>>>>>>>>>>>>>");
                    NlogHelper._logger.Info(postData);
                    HttpContent content = new StringContent(postData, Encoding.UTF8);
                    content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();//用来抛异常的
                    string responseBody = await response.Content.ReadAsStringAsync();
                    NlogHelper._logger.Info(responseBody);
                    NlogHelper._logger.Info($"【完成】请求地址{url}<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    return new Tuple<bool, string>(true, responseBody);
                } catch (WebException e) {
                    NlogHelper._logger.Warn(e);
                    NlogHelper._logger.Info($"【错误】请求地址{url}<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    return new Tuple<bool, string>(false, e.Message);
                } catch (Exception e) {
                    NlogHelper._logger.Error(e);
                    NlogHelper._logger.Info($"【错误】请求地址{url}<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    return new Tuple<bool, string>(false, e.Message);
                }
            }
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            // 总是接受  
            return true;
        }

        /// <summary>
        /// post发送字符串数据-可指定数据类型,可设置timeout
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="SendData"></param>
        /// <param name="SendData"></param>
        /// <param name="ContentType">指定数据类型(text/html, text/plain, text/css, text/javascript, image/jpeg, image/png, image/gif,application/x-www-form-urlencoded, multipart/form-data, application/json, application/xml)</param>
        /// <param name="timeout">指定超时时间</param>
        /// <param name="state">返回操作状态0:正常;远程服务器报错;数据提交超时</param>
        /// <returns></returns>
        public static string SendRequestPostData(string Url, string SendData, string ContentType, int timeout, Dictionary<string, string> headers
            , ref string Status, ref int StatusCode, string Tag, string LogName)
        {
            Status = "OK";
            System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            string strURL = Url;
            //设置最大连接数
            ServicePointManager.DefaultConnectionLimit = 200;
            //设置https验证方式
            if (Url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            if (timeout != 0)
            {
                request.Timeout = timeout;
            }
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            //内容类型
            request.ContentType = ContentType == null ? "text/html" : ContentType;
            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    request.Headers.Add(key, headers[key]);
                }
            }

            //设置参数，并进行URL编码 

            string paraUrlCoded = SendData;//System.Web.HttpUtility.UrlEncode(jsonParas);   

            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求，获得请求流 

            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception ex)
            {
                Status = ex.Message;
                //T9.Util.LogUtil.WriteLog("SendRequestPostData方法出错[0]" + (Tag != null ? "[" + Tag + "]" : "") + ":" + ex.Message + "\r\n" + ex.StackTrace, LogName);
                writer = null;
                request.Abort();
                return null;
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流
            HttpWebResponse response = null;
            string postContent = null;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                Status = ex.Status.ToString();
                //T9.Util.LogUtil.WriteLog("SendRequestPostData方法出错[1]" + (Tag != null ? "[" + Tag + "]" : "") + ":" + ex.Message + "\r\n" + ex.StackTrace, LogName);
                response = ex.Response as HttpWebResponse;
            }
            finally
            {
                if (response == null)
                {
                    postContent = null;
                }
                else
                {
                    StatusCode = (int)response.StatusCode;
                    Stream s = response.GetResponseStream();
                    StreamReader sRead = new StreamReader(s);
                    postContent = sRead.ReadToEnd();
                    request.Abort();
                    response.Close();
                    sRead.Close();
                }
            }
            return postContent;//返回Json数据
        }
    }
}

/*
 * <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.wondersgroup.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <web:queryDataStatus>
      
    <arg0>
    <infection>
	    <uniqueIndexCode>2021-11-E440005D38144DD3B59D4F107F62B1E2</uniqueIndexCode> </infection>

    </arg0></web:queryDataStatus>
       </soapenv:Body>
    </soapenv:Envelope>
 */
/****************************************************************************************
 * <?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:queryDataStatusResponse xmlns:ns2="http://webservice.wondersgroup.com/">
            <return>&lt;response&gt;
    &lt;code&gt;1&lt;/code&gt;
    &lt;msg&gt;未查到记录&lt;/msg&gt;
&lt;/response&gt;</return>
        </ns2:queryDataStatusResponse>
    </S:Body>
</S:Envelope>
 */

